package com.sws.push.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sws.common.core.domain.entity.SysUser;
import com.sws.common.core.domain.model.LoginUser;
import com.sws.common.utils.DateUtils;
import com.sws.common.utils.SecurityUtils;
import com.sws.common.utils.StringUtils;
import com.sws.customer.service.IRyCustomerService;
import com.sws.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sws.push.mapper.RyMessagePushMapper;
import com.sws.push.domain.RyMessagePush;
import com.sws.push.service.IRyMessagePushService;
import com.sws.customer.domain.RyCustomer;

/**
 * 消息推送Service业务层处理
 * 
 * @author cx
 * @date 2025-06-20
 */
@Service
public class RyMessagePushServiceImpl implements IRyMessagePushService 
{
    @Autowired
    private RyMessagePushMapper ryMessagePushMapper;

    @Autowired
    private RyMessagePushMapper baseMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IRyCustomerService ryCustomerService;

    /**
     * 查询消息推送
     * 
     * @param id 消息推送主键
     * @return 消息推送
     */
    @Override
    public RyMessagePush selectRyMessagePushById(Long id)
    {
        return ryMessagePushMapper.selectRyMessagePushById(id);
    }

    /**
     * 查询消息推送列表
     * 
     * @param ryMessagePush 消息推送
     * @return 消息推送
     */
    // RyMessagePushServiceImpl.java
    @Override
    public List<RyMessagePush> selectRyMessagePushList(RyMessagePush ryMessagePush) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null && isReceptionUser(loginUser)) {
            // 标识前台用户
            ryMessagePush.setIsReception(true);
            ryMessagePush.setPushName(loginUser.getUser().getNickName());
            ryMessagePush.setPushType("user");
        } else {
            ryMessagePush.setIsReception(false);
        }
        return ryMessagePushMapper.selectRyMessagePushList(ryMessagePush);
    }

    private boolean isReceptionUser(LoginUser loginUser) {
        return loginUser.getUser().getRoles().stream()
                .anyMatch(role -> "receptionist".equals(role.getRoleKey()));
    }
    /**
     * 新增消息推送
     * 
     * @param ryMessagePush 消息推送
     * @return 结果
     */
    @Override
    public int insertRyMessagePush(RyMessagePush ryMessagePush)
    {
        ryMessagePush.setCreateTime(DateUtils.getNowDate());
        return ryMessagePushMapper.insertRyMessagePush(ryMessagePush);
    }

    /**
     * 修改消息推送
     * 
     * @param ryMessagePush 消息推送
     * @return 结果
     */
    @Override
    public int updateRyMessagePush(RyMessagePush ryMessagePush)
    {
        ryMessagePush.setUpdateTime(DateUtils.getNowDate());
        ryMessagePush.setUpdateBy(SecurityUtils.getUsername());
        return ryMessagePushMapper.updateRyMessagePush(ryMessagePush);
    }

    /**
     * 批量删除消息推送（逻辑删除）
     */
    @Override
    public int deleteRyMessagePushByIds(Long[] ids) {
        // 更新删除标志

        int count = 0;
        for (Long id : ids) {
            RyMessagePush message = baseMapper.selectRyMessagePushById(id);
            if (message != null && message.getDelFlag() == 0) {
                message.setDelFlag(1);
                message.setUpdateTime(DateUtils.getNowDate());
                message.setUpdateBy(SecurityUtils.getUsername());
                count += baseMapper.updateRyMessagePush(message);
            }
        }

        return count;
    }



    /**
     * 删除消息推送（逻辑删除）
     */
    @Override
    public int deleteRyMessagePushById(Long id) {
        // 更新删除标志
        RyMessagePush message = baseMapper.selectRyMessagePushById(id);
        message.setUpdateTime(DateUtils.getNowDate());
        message.setUpdateBy(SecurityUtils.getUsername());

        return ryMessagePushMapper.updateDelFlagById(id);
    }

    @Override
    public int confirmRyMessagePush(Long id) {
        RyMessagePush message = baseMapper.selectRyMessagePushById(id);
        if (message == null) {
            return 0;
        }
        // 只有未确认状态可操作
        if (message.getIsConfirmed() == 0) {
            message.setIsConfirmed(1); // 更新为已确认
            message.setUpdateTime(DateUtils.getNowDate());
            message.setUpdateBy(SecurityUtils.getUsername());
            return baseMapper.updateRyMessagePush(message);
        }
        return 0;
    }

    @Override
    public int confirmRyMessagePushBatch(Long[] ids) {
        int count = 0;
        for (Long id : ids) {
            RyMessagePush message = baseMapper.selectRyMessagePushById(id);
            if (message != null && message.getIsConfirmed() == 0) {
                message.setIsConfirmed(1);
                message.setUpdateTime(DateUtils.getNowDate());
                message.setUpdateBy(SecurityUtils.getUsername());
                count += baseMapper.updateRyMessagePush(message);
            }
        }
        return count;
    }

    @Override
    public List<Map<String, Object>> selectContactList(String keyword) {
        List<Map<String, Object>> result = new ArrayList<>();

        // 查询用户
        SysUser user = new SysUser();
        user.setUserName(keyword);
        List<SysUser> users = sysUserService.selectUserList(user);
        for (SysUser u : users) { // Changed 'user' to 'u'
            Map<String, Object> map = new HashMap<>();
            map.put("id", "user_" + u.getUserId());
            map.put("name", u.getNickName());
            map.put("type", "user");
            map.put("label", u.getNickName() + " (用户)");
            result.add(map);
        }

        // 查询客户
        RyCustomer customer = new RyCustomer();
        customer.setName(keyword);
        List<RyCustomer> customers = ryCustomerService.selectRyCustomerList(customer);
        for (RyCustomer cust : customers) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", "cust_" + cust.getId());
            map.put("name", cust.getName());
            map.put("type", "customer");
            map.put("label", cust.getName() + " (客户)");
            result.add(map);
        }

        return result;
    }

}
